<template>
  <div>
    <div class="search-panel">
      <a-form-model :model="searchForm" :label-col="labelCol" :wrapper-col="wrapperCol" layout="inline">
        <a-form-model-item :label="item.conf.label" v-for="item in searchParams" :key="item.key">
          <component v-model.trim="searchForm[item.key]" :is="item.tag" :placeholder="item.conf.placeholder" :allow-clear="true">
            <a-select-option v-for="option of item.conf.options" :key="option.value" :value="option.value">
              {{ option.label }}
            </a-select-option>
          </component>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="operate-btn">
      <div class="operate-btn-left">
        <a-button @click="openDataDrawer" v-if="this.addUrl">新增</a-button>
        <a-button @click="del" v-if="this.deleteUrl">删除</a-button>
        <a-button @click="openImportExcelModal" v-if="this.importExcelUrl">导入</a-button>
        <a-button @click="exportExcel" v-if="this.exportExcelUrl">导出</a-button>
        <a-button @click="handleCustomBtn(index)" v-for="(item, index) in customBtn" :key="index">{{ item.name }}</a-button>
      </div>
      <div class="operate-btn-right">
        <a-button type="primary" @click="pageQuery">查询</a-button>
        <a-button @click="reset">重置</a-button>
      </div>
    </div>
    <div class="data-table">
      <a-table bordered :columns="columns" :data-source="tableData" :pagination="pagination" :scroll="scroll" :customRow="customRow" rowKey="rowId">
        <a-checkbox slot="customTitle" :indeterminate="indeterminate" :checked="checkAll" @change="handleCheckAll"></a-checkbox>
      </a-table>
    </div>

    <a-drawer :title="dataDrawerTitle" :width="720" :visible="showDataDrawer" :body-style="{ paddingBottom: '80px' }" @close="closeDataDrawer">
      <a-form-model :model="rowData" :label-col="labelCol" :wrapper-col="wrapperCol" layout="inline">
        <a-form-model-item :colon="false" :label="item.conf.label" v-for="item in dataParams" :key="item.key">
          <component v-model.trim="rowData[item.key]" :is="item.tag" :placeholder="item.conf.placeholder" :allow-clear="true">
            <a-select-option v-for="option of item.conf.options" :key="option.value" :value="option.value">
              {{ option.label }}
            </a-select-option>
          </component>
        </a-form-model-item>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '10px' }" type="primary" @click="add" v-if="this.dataDrawerTitle === '新增' && this.addUrl">
          提交
        </a-button>
        <a-button :style="{ marginRight: '10px' }" type="primary" @click="update" v-else-if="this.updateUrl">
          提交
        </a-button>
        <a-button @click="closeDataDrawer">取消</a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
  export default {
    props: {
      bookTitle: {
        type: String,
        required: true,
      },
      searchParams: {
        type: Array,
        required: true,
      },
      dataParams: {
        type: Array,
        required: true,
      },
      tableColumns: {
        type: Array,
        required: true,
      },
      scroll: {
        type: Object,
      },
      pageQueryUrl: String,
      queryDetailUrl: String,
      addUrl: String,
      deleteUrl: String,
      updateUrl: String,
      importExcelUrl: String,
      exportExcelUrl: String,
      customBtn: Array,
    },
    data() {
      return {
        searchForm: {},
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
        pagination: {
          current: 1,
          pageSize: 15,
          total: 0,
          showSizeChanger: true,
          pageSizeOptions: ['15', '25', '35'],
          showTotal: (total) => `共 ${total} 条`,
          onChange: (current, pageSize) => this.pageChange(current, pageSize),
          onShowSizeChange: (current, pageSize) => this.pageSizeChange(current, pageSize),
        },
        columns: [],
        tableData: null,
        showDataDrawer: false,
        dataDrawerTitle: null,
        rowData: {},
        currentMouseenter: null,
        selectedRowKeys: [],
        indeterminate: false,
        checkAll: false,
      };
    },
    created() {
      const serial = [
        {
          dataIndex: 'number',
          customRender: (text, record, index) => {
            return (
              <span onMouseenter={() => this.handleMouseEnter(record, index)} onMouseleave={() => this.handleMouseLeave(record, index)}>
                {this.currentMouseenter === index || this.selectedRowKeys.includes(index) ? (
                  <a-checkbox checked={this.selectedRowKeys.includes(index)} onChange={(e) => this.handleCheck(index, e)}></a-checkbox>
                ) : (
                  <span>{(this.pagination.current - 1) * this.pagination.pageSize + index + 1}</span>
                )}
              </span>
            );
          },
          slots: { title: 'customTitle' },
          align: 'center',
          width: 50,
        },
      ];
      this.columns = [...serial, ...this.tableColumns];
      this.pageQuery();
    },
    methods: {
      handleMouseEnter(record, index) {
        this.currentMouseenter = index;
      },
      handleMouseLeave() {
        this.currentMouseenter = null;
      },
      handleCheck(index, e) {
        if (e && e.target && e.target.checked) {
          this.selectedRowKeys.push(index);
          this.indeterminate = this.selectedRowKeys.length === this.tableData.length ? false : true;
          this.checkAll = this.selectedRowKeys.length === this.tableData.length ? true : false;
        } else {
          this.selectedRowKeys = this.selectedRowKeys.filter((item) => item !== index);
          this.indeterminate = this.selectedRowKeys.length === 0 ? false : true;
          this.checkAll = false;
        }
      },
      handleCheckAll(e) {
        this.indeterminate = false;
        this.checkAll = e.target.checked;
        if (this.selectedRowKeys.length === this.pagination.pageSize) {
          this.selectedRowKeys = [];
        } else {
          this.selectedRowKeys = [];
          for (let i = 0; i < this.tableData.length; i++) {
            this.selectedRowKeys.push(i);
          }
        }
      },
      customRow(record, index) {
        return {
          on: {
            click: (e) => {
              if (e.target.type === 'checkbox') {
                return false;
              }
              console.log(index);
              this.rowData = record;
              this.showDataDrawer = true;
              this.dataDrawerTitle = '查看/编辑';
            },
          },
        };
      },
      pageQuery() {
        this.selectedRowKeys = [];
        this.indeterminate = false;
        this.checkAll = false;
        const url = this.pageQueryUrl.replace('{page}', this.pagination.current).replace('{pageSize}', this.pagination.pageSize);
        this.axios.post(url, this.searchForm).then((res) => {
          this.pagination.total = res.total ? res.total : 0;
          this.tableData = res.table ? res.table : [];
        });
        this.$forceUpdate();
      },
      pageChange(current) {
        this.pagination.current = current;
        this.pageQuery();
      },
      pageSizeChange(current, pageSize) {
        this.pagination.current = 1;
        this.pagination.pageSize = pageSize;
        this.pageQuery();
      },
      reset() {
        this.pagination.current = 1;
        this.pagination.pageSize = 15;
        for (const item in this.searchForm) {
          this.searchForm[item] = undefined;
        }
        this.pageQuery();
      },
      add() {
        this.axios.post(this.addUrl, this.rowData).then((res) => {
          if (res.code === 'ok') {
            this.reset();
            this.$message.success('新增成功', 3);
            this.closeDataDrawer();
          } else {
            this.$message.error(res.message);
          }
        });
      },
      update() {
        this.axios.post(this.updateUrl, this.rowData).then((res) => {
          if (res.code === 'ok') {
            this.reset();
            this.$message.success('修改成功', 3);
            this.closeDataDrawer();
          } else {
            this.$message.error(res.message);
          }
        });
      },
      del() {
        if (this.selectedRowKeys.length == 0) {
          this.$message.warn('请至少选择一行数据');
          return;
        }
        const deleteIdList = [];
        for (const key of this.selectedRowKeys) {
          deleteIdList.push(this.tableData[key].id);
        }
        this.axios.post(this.deleteUrl, deleteIdList).then((res) => {
          if (res.code === 'ok') {
            this.reset();
            this.$message.success('删除成功', 3);
          } else {
            this.$message.error(res.message);
          }
        });
      },
      openDataDrawer() {
        this.rowData = {};
        this.dataDrawerTitle = '新增';
        this.showDataDrawer = true;
      },
      closeDataDrawer() {
        this.showDataDrawer = false;
      },
      openImportExcelModal() {
        this.showDataDrawer = true;
      },
      exportExcel() {},
      handleCustomBtn(index) {
        this.$emit('custom-btn', index);
      },
    },
  };
</script>

<style scoped>
  .book-title {
    font-size: 16px;
    font-weight: bold;
    padding: 10px;
  }
  .operate-btn {
    display: flex;
    justify-content: space-between;
  }
  .operate-btn-left >>> .ant-btn,
  .operate-btn-right >>> .ant-btn {
    margin: 10px;
  }
</style>
